package com.mobile.ado.contacts;

import java.util.ArrayList;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;

import com.mobile.ado.R;
import com.mobile.ado.util.ContactsUtil;
import com.mobile.ado.util.ContentProviderHelper;

public class ContactsActivity extends Activity implements OnClickListener {

	private EditText searchEditText;
	private ListView listView;
	private ImageButton okImageButton;

	private Intent intent;

	ArrayList<Contact> selectedContacts;
	private ArrayList<Integer> selectedIndex;
	private ArrayList<Contact> contacts;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contacts);

		intent = getIntent();

		selectedContacts = new ArrayList<Contact>();

		initSearchEditText();
		initContactsListView();

		okImageButton = (ImageButton) findViewById(R.id.okButton);
		okImageButton.setOnClickListener(this);

	}

	private void initContactsListView() {
		listView = (ListView) findViewById(R.id.contactsListView);
		Cursor contactsCursor = null;
		if (isSearch() == false) {
			contactsCursor = ContentProviderHelper
					.getAllSystemContactsWithoutAnySelection(this);

		} else {
			contactsCursor = getSearchResult();

		}
		contacts = ContactsUtil.getAllContacts(this, contactsCursor);

		selectedIndex = new ArrayList<Integer>();
		ContactListAdapter adapter = new ContactListAdapter(this, contacts,
				selectedIndex);

		listView.setAdapter(adapter);

	}

	private boolean isSearch() {
		return intent.getAction() != null
				&& intent.getAction().equals(Intent.ACTION_SEARCH);
	}

	private Cursor getSearchResult() {
		Cursor contactsCursor;
		String query = intent.getStringExtra(SearchManager.QUERY);
		contactsCursor = ContentProviderHelper.getAllSystemContactsByName(this,
				query);
		return contactsCursor;
	}

	private void initSearchEditText() {
		searchEditText = (EditText) findViewById(R.id.searchEditText);
		OnClickListener listener = new OnClickListener() {

			@Override
			public void onClick(View view) {
				// TODO Auto-generated method stub
				onSearchRequested();
			}
		};

		searchEditText.setOnClickListener(listener);

		if (intent.getAction() != null && isSearch()) {
			searchEditText.setVisibility(View.GONE);
		}
	}

	@Override
	public void onClick(View v) {

		for (int i = 0; i < selectedIndex.size(); i++) {
			selectedContacts.add(contacts.get(selectedIndex.get(i)));
		}

		Intent intent = new Intent();
		intent.putExtra("selectedContacts", selectedContacts);
		setResult(RESULT_OK, intent);
		this.finish();
	}

}
